<?php

namespace App\Jobs;

use App\Services\BookTitleService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;


class UpdateBtPageNum implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $tableExt;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tableExt)
    {
        $this->tableExt = $tableExt;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $tableExt = $this->tableExt;
        DB::table("book_titles_$tableExt as bt")
            ->join("book_catalogs_$tableExt as bc", 'bt.id', '=', 'bc.book_title_id')
            ->whereNull('bt.deleted_at')
            ->whereNull('bc.deleted_at')
            ->select('bt.id', 'bc.serial_no', 'bc.page_num')
            ->chunkById(
                200,
                function ($list) {
                    if (!empty($list)) {
                        $btIdSerialNos = [];
                        $list = $list->toArray();
                        foreach ($list as $val) {
                            $tmp['serial_no'] = $val->serial_no;
                            $tmp['page_num']  = $val->page_num;
                            $btIdSerialNos[$val->id][] = $tmp;
                        }
                        foreach ($btIdSerialNos as $key => $val) {
                            $res     = BookTitleService::getSerialNoPageNum($val);
                            $pageNum = array_sum(array_values($res));
                            info($this->tableExt.'---id='.$key.'---'.$pageNum);
                            DB::table("book_titles_$this->tableExt")->where('id', $key)->update(['page_num' => $pageNum]);
                        }
                    }
                },
                'bt.id',
                'id'
            );
    }

}
